<template>
  <el-form :inline="true" :model="form" class="dynamicQueryForm-inline">
    <!-- 【1】匹配范围：字段选择 + 动态输入 -->
    <!-- 只有传递了 showMatchRange 才渲染该组 -->
    <el-form-item label="匹配范围" v-if="showMatchRange">
      <el-select
        v-model="form.matchField"
        style="width: 200px; margin-right: 10px"
        placeholder="请选择字段"
        clearable
        @change="onMatchFieldChange"
      >
        <el-option
          v-for="item in columnsValues"
          :key="item.prop"
          :label="item.label"
          :value="item.prop"
        />
      </el-select>

      <component
        :is="matchInputComponent"
        v-model="form.matchValue"
        :style="{ width: '240px' }"
        :placeholder="`请输入${matchFieldLabel}`"
        clearable
        v-bind="matchInputProps"
      >
        <!-- 如果是 select，需要手动渲染 options -->
        <el-option
          v-if="matchFieldConfig.type === 'select' && matchFieldConfig.options"
          v-for="opt in matchFieldConfig.options"
          :key="opt.value"
          :label="opt.label"
          :value="opt.value"
        />
      </component>
    </el-form-item>

    <!-- 【2】其他条件：动态渲染 -->
    <template v-for="field in extraFields" :key="field.prop">
      <el-form-item :label="field.label">
        <component
          :is="getInputComponent(field.type)"
          v-model="form[field.prop]"
          :style="{ width: field.width || '180px' }"
          :placeholder="field.placeholder || `请输入${field.label}`"
          clearable
          v-bind="getFieldProps(field)"
        >
          <el-option
            v-if="field.type === 'select' && field.options"
            v-for="opt in field.options"
            :key="opt.value"
            :label="opt.label"
            :value="opt.value"
          />
        </component>
      </el-form-item>
    </template>

    <!-- 【3】操作按钮 -->
    <el-form-item>
      <el-button type="primary" @click="onSubmit">查询</el-button>
      <el-button @click="onReset">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { dayjs } from 'element-plus';
import { cloneDeep } from 'lodash';
import { ref, computed, onMounted, onUnmounted } from 'vue';

// ========== Props ==========
const props = defineProps<{
  // 控制“匹配范围”是否出现：传了才渲染，true/false 控制显隐
  showMatchRange?: boolean;
  // 匹配范围字段列表
  columnsValues: any;
  // 其他独立条件
  extraFields: any;
}>();

// ========== Emits ==========
const emit = defineEmits(['submit', 'reset']);

// ========== 数据 ==========
const form = ref<{
  matchField: string;
  matchValue: string;
  [key: string]: any;
}>({
  matchField: '', // 默认手机号
  matchValue: ''
  // 其他字段会在 mounted 中初始化
});

// ========== 计算属性 ==========
// 当前匹配字段配置
const matchFieldConfig = computed(() => {
  return props.columnsValues?.find((item: any) => item.prop === form.value.matchField) || {};
});

const matchFieldLabel = computed(() => matchFieldConfig.value.label || '内容');

const matchInputComponent = computed(() => {
  const map: Record<string, string> = {
    text: 'el-input',
    date: 'el-date-picker',
    select: 'el-select',
    number: 'el-input-number',
    switch: 'el-switch'
  };
  return map[matchFieldConfig.value.type] || 'el-input';
});

const matchInputProps = computed(() => {
  if (matchFieldConfig.value.type === 'date') {
    return { type: 'date', valueFormat: 'YYYY-MM-DD HH:mm:ss' };
  }
  return {};
});

// ========== 方法 ==========
const getInputComponent = (type: string) => {
  const map: Record<string, string> = {
    text: 'el-input',
    date: 'el-date-picker',
    select: 'el-select',
    number: 'el-input-number',
    switch: 'el-switch'
  };
  return map[type] || 'el-input';
};

const getFieldProps = (field: any) => {
  return field.params ? { ...(field.params || {}) } : {};
};

const onMatchFieldChange = () => {
  form.value.matchValue = '';
};

const onSubmit = () => {
  // 删除 extraFields 中的空值
  props.extraFields.forEach((field: any) => {
    if (form.value[field.prop] === '') {
      delete form.value[field.prop];
    }
  });
  let returnedParams: any = cloneDeep(form.value);
  // 将matachKey 和 matchValue 转换为 key:value
  // 转换后删除掉
  if (form.value.matchField) {
    returnedParams[returnedParams.matchField] = returnedParams.matchValue;
  }

  // 处理时间区间参数（订单创建时间）
  if (returnedParams.orderInDate) {
    returnedParams.params = {
      beginOrderTime: dayjs(returnedParams.orderInDate[0])
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss'),
      endOrderTime: dayjs(returnedParams.orderInDate[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
    };
  }

  // 转换 params.orderSignTime 为  returnedParams.params = {orderSignTime}
  returnedParams = normalizeParamsConfig(returnedParams);
  // 删除映射key
  delete returnedParams.matchField;
  delete returnedParams.matchValue;
  delete returnedParams.orderInDate;
  emit('submit', returnedParams);
};

// 自动把 config 中的 prop: "params.xxx"  转成 params: { xxx: ... }
function normalizeParamsConfig(returnedParams: any) {
  const params: any = {};

  // 遍历 returnedParams 的所有 key
  for (const key in returnedParams) {
    if (key.startsWith('params.')) {
      const realKey = key.replace('params.', '');
      params[realKey] = returnedParams[key];

      // 删除原始的 params.xx key
      delete returnedParams[key];
    }
  }

  // 合并进入 returnedParams.params
  returnedParams.params = {
    ...(returnedParams.params || {}),
    ...params
  };

  return returnedParams;
}

const onReset = () => {
  form.value = {
    matchField: '',
    matchValue: ''
  };
  props.extraFields.forEach((field: any) => {
    form.value[field.prop] = '';
  });
  emit('reset');
};

const handleEnter = (e: KeyboardEvent) => {
  if (e.key === 'Enter') {
    onSubmit();
  }
};

// 初始化 extraFields 的 form 字段
onMounted(() => {
  props.extraFields?.forEach((field: any) => {
    if (!(field.prop in form.value)) {
      form.value[field.prop] = '';
    }
  });

  // 【功能：默认选中手机号搜索】
  // 检查可选搜索字段列表中是否包含接收人手机号(receiverPhone)选项
  // 如果存在，则将其设置为默认选中的搜索范围
  const phoneField = props.columnsValues.find((item: any) => item.prop === 'receiverPhone');
  if (phoneField) {
    // 将form表单中的region字段(搜索范围)设置为receiverPhone
    // 这样用户进入页面时就会默认以手机号作为搜索条件
    form.value.matchField = 'receiverPhone';
  }

  // 监听全局回车
  window.addEventListener('keydown', handleEnter);
});

onUnmounted(() => {
  // 页面销毁自动清理
  window.removeEventListener('keydown', handleEnter);
});
</script>

<style lang="scss">
.dynamicQueryForm-inline {
  .el-form-item {
    margin-bottom: 20px;
  }
}
</style>
